package com.oydsoft.auth.service;

import com.oydsoft.auth.dto.S01;
import com.oydsoft.auth.dto.S03;
import com.oydsoft.auth.mapper.AuthMapper;
import com.oydsoft.common.ext.S01Ext;
import com.oydsoft.common.util.BCryptUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    ClientDetailsService clientDetailsService;

    @Autowired
    private AuthMapper authMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //取出身份，如果身份为空说明没有认证
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //没有认证统一采用httpbasic认证，httpbasic中存储了client_id和client_secret，开始认证client_id和client_secret
        if(authentication==null){
            ClientDetails clientDetails = clientDetailsService.loadClientByClientId(username);
            if(clientDetails!=null){
                //密码
                String clientSecret = clientDetails.getClientSecret();
                clientSecret = BCryptUtil.encode(clientSecret);
                return new User(username,clientSecret,AuthorityUtils.commaSeparatedStringToAuthorityList(""));
            }
        }
        if (StringUtils.isEmpty(username)) {
            throw new UsernameNotFoundException("用户名为空!");
        }
        S01 s01 = authMapper.getInfoByUserName(username);
        if (s01==null){
            throw new UsernameNotFoundException("用户不存在！");
        }
        /*S01Ext userext = new S01Ext();
        userext.setA0101("admin");  //账号
        userext.setS0170(BCryptUtil.encode("admin")); //存入密码时加密
        userext.setPermissions(new ArrayList<S03>());//权限暂时用静态的

        //取出正确密码（hash值）
        String password = userext.getS0170();
        //用户权限，这里暂时使用静态数据，最终会从数据库读取
        //从数据库获取权限
        List<S03> permissions = userext.getPermissions();
        if(permissions == null){
            permissions = new ArrayList<>();
        }
        List<String> user_permission = new ArrayList<>();
        permissions.forEach(item-> user_permission.add(item.getS0301()));
        //使用静态的权限表示用户所拥有的权限
//        user_permission.add("");//
//        user_permission.add("");//
        String user_permission_string  = StringUtils.join(user_permission.toArray(), ",");
        UserJwt userDetails = new UserJwt(username,password,AuthorityUtils.commaSeparatedStringToAuthorityList(user_permission_string));
        userDetails.setId(userext.getS01Id());
        userDetails.setPhone(userext.getS0114());
        userDetails.setCardId(userext.getS0110());
        userDetails.setEmail(userext.getS0117());
        userDetails.setName(username);
        userDetails.setNickName(userext.getS0109());//用户昵称
        userDetails.setA01Id(userext.getA01Id());*/
        List<S03> userPermissinList = authMapper.getUserPermissinList(username);
        List<String> user_permission = new ArrayList<>();
        userPermissinList.forEach(item-> user_permission.add(item.getS0303()));
        UserJwt userDetails = new UserJwt(username,BCryptUtil.encode(s01.getS0170()),AuthorityUtils.commaSeparatedStringToAuthorityList(StringUtils.join(user_permission.toArray(), ",")));
        return userDetails;
    }
}
